package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 *@ClassName RpcServer
 *@Description  客户端发送请求时指定 replyTo 地址和 correlationID，
 * 服务端处理请求后根据 replyTo 地址发送响应，并在响应中附带相同的 correlationID。
 *@Author ZJX
 *@Date 2025/1/8 06:32
 *@Version 1.0
 **/
public class RpcServer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//        1. 创建连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();


//        2. 创建 channel
        Channel channel = connection.createChannel();

//        3. 接受请求
        channel.basicQos(1);
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String request = new String(body);
                System.out.println("接收到Connection请求"+request);
                String response = "根据request: "+request+", 响应成功";
                AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                channel.basicPublish("",Constants.RPC_RESPONSE_QUEUE,basicProperties,response.getBytes(StandardCharsets.UTF_8));
//                 对消息进⾏应答
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(Constants.RPC_REQUEST_QUEUE,false,consumer);
    }
}
